package com.adam.example.aggregation.bucket;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.*;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.adam.example.ElasticsearchClientHolder;

import java.io.IOException;
import java.util.List;

public class TermsAggregationExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient elasticsearchClient = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        SearchResponse<Void> searchResponse = elasticsearchClient.search(builder -> builder
                        .index("test_books")
                        .size(0)
                        .aggregations("agg", aggregationBuilder -> aggregationBuilder
                                .terms(termsAggregationBuilder -> termsAggregationBuilder
                                        .field("language")
                                )
                                .aggregations("avgPrice", aggregationBuilder1 -> aggregationBuilder1
                                        .avg(averageAggregationBuilder -> averageAggregationBuilder
                                                .field("price")
                                        )
                                )
                        )
                , Void.class);
        Aggregate aggregate = searchResponse.aggregations().get("agg");
        StringTermsAggregate stringTermsAggregate = aggregate.sterms();
        Buckets<StringTermsBucket> buckets = stringTermsAggregate.buckets();
        List<StringTermsBucket> bucketList = buckets.array();
        for(int i=0;i<bucketList.size();i++) {
            StringTermsBucket bucket = bucketList.get(i);
            System.out.println("[" + (i+1) + "]" + bucket.key() + ":" + bucket.docCount());
            Aggregate aggregate1 = bucket.aggregations().get("avgPrice");
            AvgAggregate avgAggregate = aggregate1.avg();
            System.out.println("avg price:" + avgAggregate.value());
        }

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
